<?

class AuthController extends MainController implements ControllerInterface {

	/**
	 * Strona glowna
	 *
	 */

	public function IndexAction($param) {
		$this->AddDescription("");
		$this->AddTitle("");
		
	}
	
	
	public function RegisterValidationAction($param, $as_action = true)
	{	
		
		if ($as_action)
				$param['validation_data'] = array();	
		
		$validator = new Validator($param['validation_data']);
		$validator->IsEmpty('first_name', $this->t('Enter your name'));
		$validator->IsString('field_name', $this->t('Enter your name'));
		$validator->IsEmpty('last_name', $this->t('Enter your family name'));
		$validator->IsString('last_name', $this->t('Enter your family name'));
		$validator->IsEmailAddress('email', $this->t('Enter your email'));
		$validator->IsEmpty('email', $this->t('Enter your email'));
		$validator->IsEmpty('email2', $this->t('Reenter your email'));
		$validator->IsNotEqual('email2', 'email', $this->t('Emails aren\'t same'));
		$validator->IsShorter('password', 4, $this->t('Password should be longer than 4 characters'));
		$validator->IsEmpty('password', $this->t('Enter password'));
		$validator->IsEmpty('password2', $this->t('Reenter your password'));
		$validator->IsNotEqual('password2', 'password', $this->t('Passwords aren\'t same'));
		$validator->IsValidOnline('email', $this->t('Specified email address is already registered'), Router::GenerateUrl('ajaxCheckEmail'));
		$validator->IsEmpty('rules1', $this->t('Accept rules'));
		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();		
	}
	
	public function AjaxCheckEmailAction($param) {
		$this->setAjaxRender();
		$this->partialTemplate = 'clean.tpl';

		$email = Request::GetGet('email');

		$dalData = UserDAL::GetDalDataObj();
		
		if($this->userLoggedIn) 
		{
			// jesli user zalogowany - moze nadpisac swoj mail
			$dalData->addCondition('id', $this->user->getId() . ' AND (email = \'' . $email . '\' OR new_email = \'' . $email . '\')' , '!=');
		} else {
			$dalData->addCondition('email', '\'' . $email . '\'', '=' , 'AND');
			$dalData->addCondition('new_email', '\'' . $email . '\'', '=' , 'OR');			
		}
		
		$res = UserDAL::GetResult($dalData);
		
		if ($res)
			$this->content = 'false';
		else
			$this->content = 'true';
	}	
	
	
	public function RegisterAction($param)
	{
		$this->AddDescription($this->t('Sign in'));
		$this->AddTitle("Sign in");
		$this->AddBreadCrumb("Sign in");
		
		if($this->userLoggedIn)
		{
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}	
		if(Request::IsPost() && Request::GetPost('action') == 'register')
		{
			$data = Request::GetAllPost();
			$errors = array();
			if(empty($errors))
			{
				$_now = date('Y-m-d H:i:s', time());
				$user = new User();
				$user->setStatus(1);
				$user->setActive(0);
				$user->setOnline(0);
				$user->setEmail($data['email']);
				$user->setPassword(UserDAL::GeneratePassword($data['password']));
				$user->setFirstName($data['first_name']);
				$user->setLastName($data['last_name']);
				$user->setDateInsert($_now);
				$user->setdateUpdate($_now);
//				$user->setLastLogin($_now);
				$userId = UserDAL::Insert($user->GetDalDataObj());
				
				$extProfile = new UserExtendedProfile();
				$extProfile->setIdUser($userId);
				UserExtendedProfileDAL::Insert($extProfile->GetDalDataObj());
				
				SessionProxy::SetValue('_user_id_', $userId);
				SessionProxy::SetValue('_redirect_from_register_', true);
				
				return $this->AddRedirect(Router::GenerateUrl('sendConfirmationEmail'), 0);
				
			}
		} else {
			$this->addScript('jquery-validate/jquery.validate.js');
			$this->AddScript(Router::GenerateUrl('signInValidation') . '?id_f=registerForm');
		}
		
	}
	
	public function SendConfirmationEmailAction($param)
	{
		$this->AddDescription("");
		$this->AddTitle("");
		
		if($this->userLoggedIn)
		{
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
		$_isFromeregister = SessionProxy::GetValue('_redirect_from_register_', False);
		$_userId = SessionProxy::GetValue('_user_id_', 0);
		if($_isFromeregister && $_userId)
		{
			// przekierowanie z rejestracji
			SessionProxy::ClearValue('_redirect_from_register_');
			
			$user = UserDAL::GetResult(
						UserDAL::GetDalDataObj(
							array(
								'condition' => array(
									'id' => array($_userId),
									'active' => array(0)
								)
							)
						)
					);
			if(count($user) != 1)
			{
				return $this->AddRedirect(Router::GenerateUrl('default'), 0);
			}
			
			$hash = UserDAL::GenerateHash();
			
			$user[0]->setHash($hash);
			UserDAL::Update($user[0]->getDalDataObj());
			
			$this->smarty->assign('hash', $hash);
			
			/* @todo: wysyłąnei maila */
			// wyslanei maila
			$mailer = new Mailer(SMTP_PORT);
			$this->smarty->assign('hash', $hash);
			$bodyHTML = $this->smarty->fetch('partial/Auth/email/ConfirmRegistrationHTML.tpl');
			$this->smarty->assign('hash', $hash);
			$bodyPlain = $this->smarty->fetch('partial/Auth/email/ConfirmRegistrationPlain.tpl');
			
			$a = $mailer->SendEmail($bodyHTML, $bodyPlain, $this->t('Please confirm your email address'), $user[0]->getEmail());
			
			$this->smarty->assign('email', $user[0]->getEmail());
			
			
			
		} else {
			return $this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
		
	}
	
	public function ConfirmAccountAction($param)
	{
		$this->AddDescription($this->t('Confirm account'));
		$this->AddTitle("Confirm account");
		$hash = $param['hash'];
		
		$res = UserDAL::ConfirmRegistration($hash);
		
		if($res)
		{
			$this->AddRedirectInfo($this->T('Your account is active'));
			$this->AddRedirect(Router::GenerateUrl('default'), 0);
		} else {
			$this->AddRedirectInfo($this->T('An error occurred during activation'));
			$this->AddRedirect(Router::GenerateUrl('default'), 0);
		}
		
		
	}
	
	public function LoginValidationAction($param, $as_action = true)
	{
		if ($as_action)
				$param['validation_data'] = array();	
		
		$validator = new Validator($param['validation_data']);
		$validator->IsEmpty('login', $this->t('Enter your email'));
		$validator->IsEmpty('password', $this->t('Enter password'));
		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		return $validator->getErrorList();		
	}
	
	// logowanie
	public function LoginAction($param)
	{
		$this->AddDescription($this->t('Login'));
		$this->AddTitle("Login");	
		$this->AddBreadCrumb("Login");

		
		if(Request::IsPost())
		{
			if($this->userLoggedIn)
			{
				$_urls = SessionProxy::GetValue('_user_urls_history_');

				$_i = count($_urls);

				$_lastlogin = $this->user->getLastLogin();
				if($_lastlogin == '0000-00-00 00:00:00')
				{
					$this->AddRedirectInfo($this->t('Please complete your details'));
					return $this->AddRedirect(Router::GenerateUrl('editProfile'), 0);
				} else {
					return $this->AddRedirect(Router::GenerateUrl('default'), 0);
				}
				

			} else {
				$this->smarty->assign('loginError', true);
			}
		
		} else {
			if($this->userLoggedIn)
			{
				return $this->AddRedirect(Router::GenerateUrl('default'), 0);
			}
			$this->smarty->assign('loginError', false);
		}
		
		$this->addScript('jquery-validate/jquery.validate.js');
		$this->AddScript(Router::GenerateUrl('logInValidation') . '?id_f=loginForm');		

	}
	
	// wylogowanie
	public function LogoutAction($param)
	{
		$this->AddDescription("");
		$this->AddTitle("");	
		
		$_user = SessionProxy::GetValue('logged_user');
		$_user->setOnline(0);
		UserDAL::Update($_user->getDalDataObj());
		
		
		SessionProxy::ClearValue('logged_user');
		
		$this->AddRedirect(Router::GenerateUrl('default'), 0);
	}
	
	public function CheckUser($param)
	{
		
		if(!empty(Router::$curLabel))
		{
			$_urls = SessionProxy::GetValue('_user_urls_history_', array());
			$_i = count($_urls);
			// jesli nie ma przekierowania na ta sama strone
			
			
			
			if(isset($_urls[$_i - 1]))
			{
				if( $_urls[$_i - 1]['label'] != Router::$curLabel) 
				{
					if($_i > 2)
					{
						array_shift($_urls);
					}
					$_urls[] = array('label'=>Router::$curLabel, 'params' => $param);
					SessionProxy::SetValue('_user_urls_history_', $_urls);				
				}
			} else {
					$_urls[] = array('label'=>Router::$curLabel, 'params' => $param);
					SessionProxy::SetValue('_user_urls_history_', $_urls);					
			}
		}
		
		
		//czy i skąd się logujemy
		$login_action = Request::Check('login_action') ? Request::GetPost('login_action') : null;
		
		$user = null;
		$msg = null;

		switch($login_action)
		{
			case 'login':
				$login = Request::GetPost('login');
				$password = Request::GetPost('password');

				$_user = UserDAL::GetResult(
						UserDAL::GetDalDataObj(array(
							'condition' => array(
								'email' => array($login),
								'password' => array(UserDAL::GeneratePassword($password))
							)
						)));


				if(isset($_user[0]) && count($_user) == 1)
				{
					SessionProxy::SetValue('logged_user', $_user[0]);
					$user = $_user[0];
					$user->setOnline(0);
					$user->setLastLogin(date('Y-m-d H:i:s', time()));
					UserDAL::Update($user->getDalDataObj());
					if(Router::$curLabel != 'logIn')
					{
						$this->AddRedirect(Router::GenerateUrl('default'), 0);
					}
				}					
				break;

			case 'logout':

				break;

			// sprawdzamy usera
			default:
				$user = SessionProxy::GetValue('logged_user');
		}

		return array($user, !is_null($user), $msg);
	}		
	



	/**
	 * Czesc wspolna wszystkich podstron
	 *
	 */
	public function PreDispatch($param) {
		$this->Run($param);
	}

	public function PostDispatch($param) {
		
		// nagłówek strony
		$this->RunShared('Header', $param);
		
		// footer
		$this->RunShared('Footer', $param);
	}

}

